from django.shortcuts import render, redirect
from django.views import View
from QQLoginTool.QQtool import OAuthQQ
from . import constants
from django.http import JsonResponse
from .models import OAuthQQUser
from django.contrib.auth import login
from django.core.signing import TimestampSigner
from users.models import User
from django.http import HttpResponseForbidden
from django.contrib.auth import authenticate
from django_redis import get_redis_connection


class QQauthURLView(View):
    def get(self, request):
        next = request.GET.get('next')
        oauth = OAuthQQ(client_id=constants.QQ_CLIENT_ID, client_secret=constants.QQ_CLIENT_SECRET,
                        redirect_uri=constants.QQ_REDIRECT_URI, state=next)
        login_url = oauth.get_qq_url()
        return JsonResponse({'login_url': login_url})


class QQAuthUserView(View):
    def get(self, request):
        code = request.GET.get('code')
        state = request.GET.get('state')
        oauth = OAuthQQ(client_id=constants.QQ_CLIENT_ID, client_secret=constants.QQ_CLIENT_SECRET,
                        redirect_uri=constants.QQ_REDIRECT_URI)
        access_token = oauth.get_access_token(code)
        openid = oauth.get_open_id(access_token)
        try:
            qquser = OAuthQQUser.objects.get(openid=openid)
        except:
            singner = TimestampSigner()
            value = singner.sign(openid)
            context = {'token': value}
            return render(request, 'oauth_callback.html', context)
        login(request, qquser.user)
        response = redirect(state)
        response.set_cookie('username', qquser.user.username, max_age=constants.MA)
        return response

    def post(self, request):
        access_token = request.POST.get('access_token')
        mobile = request.POST.get('mobile')
        password = request.POST.get('pwd')
        sms_code = request.POST.get('sms_code')

        if not all([access_token, mobile, password, sms_code]):
            return HttpResponseForbidden('表单信息不全')
        singner = TimestampSigner()
        openid = singner.unsign(access_token)
        if not openid:
            return HttpResponseForbidden('登录信息失效')
        redis_coom = get_redis_connection('verify_code')
        sms_code_server = redis_coom.get('sms_%s' % mobile)
        if not sms_code_server:
            return HttpResponseForbidden('验证码已失效')
        sms_code_server = sms_code_server.decode()
        if sms_code_server != sms_code:
            return HttpResponseForbidden('验证码输入错误')
        if User.objects.filter(mobile=mobile).count() == 0:
            try:
                User.objects.create_user(username=mobile, password=password, mobile=mobile)
            except:
                return render(request, 'oauth_callback.html', {'account_errmsg': '用户创建失败'})
        user = authenticate(username=mobile, password=password)
        if not user:
            return render(request, 'oauth_callback.html', {'account_errmsg': '用户名或密码错误'})
        try:
            OAuthQQUser.objects.create(openid=openid, user=user)
        except:
            return render(request, 'oauth_callback.html', {'account_errmsg': '关联失败'})
        login(request, user)
        next = request.GET.get('state')
        response = redirect(next)
        response.set_cookie('username', user.username, max_age=constants.MA)
        return response
